<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <link rel="stylesheet" href="../css/login.css">
  <title>用户登录</title>
</head>
<body>
  <div id="login_box">
    <h2>登录</h2>

    <div id="input_box">
      <input type="text" placeholder="请输入用户名" id="username">
    </div>
    <div class="input_box">
      <input type="password" placeholder="请输入密码" id="password">
    </div>

    <button id="login">登录</button>
    <button id="register">注册</button>
  </div>

  <script>
    const loginBtn = document.getElementById('login');
    const registerBtn = document.getElementById('register');

    const nameText = document.getElementById("username");
    const passwordText = document.getElementById('password');

    loginBtn.addEventListener('click', () => {
      const userPattern = /^[A-z0-9]{6,20}$/;
      const passwordPattern = /^[a-zA-Z0-9]{8,15}$/;

      if (!userPattern.test(nameText.value)) {
        alert('用户名由6-20位字母、数字组成！');
        return;
      }
      if (!passwordPattern.test(passwordText.value)) {
        alert('密码由8-15位字母、数字组成！');
        return;
      }
      
      if (nameText.value.length && passwordText.value.length ) {
        axios.get('http://localhost:8080/account/accountLogin', {
            params: {
              username: nameText.value,
              password: passwordText.value
            }
          }).then(function(res) {
            if (typeof(res.data) == 'string') {
              alert(res.data);

              return;
            }

            const {username, password} = res.data;
            if (username.length && password.length) {
              localStorage.setItem('username', username);
              localStorage.setItem('password', password);

              window.location.href = '../index.html';
            }
          }).catch(function(err) {
            console.log(err);
          });
      } else {
        alert('请输入用户名或密码');
      }
    })

    registerBtn.addEventListener('click', () => {
      window.location.href = './register.html';
    })
  </script>
</body>
</html>